package com.smartcruise;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.multidex.MultiDex;

import com.amap.api.maps.MapsInitializer;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.smartcruise.main.MainActivity;
import com.smartcruise.start.flashActivity.FlashActivity;
import com.smartcruise.util.FileUtils;
import com.smartcruise.util.SPUtils;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import io.realm.Realm;
import io.realm.RealmConfiguration;

/**
 * Created by FengChaoQun
 * on 2018/1/18 0018
 */

public class MyApplication extends Application {

    private static MyApplication instance;
    public Activity currentActivity;
    private Map<String, Activity> mList = new HashMap<>();
    private Realm realm;

    public static MyApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (instance == null) {
            instance = this;
        }
        //      初始化数据库
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
        Realm.setDefaultConfiguration(config);
        realm = Realm.getDefaultInstance();

        //初始化极光推送
        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.init(this);

        //设置地图路径
        MapsInitializer.sdcardDir = FileUtils.getMapPath();

        initBugly();

        initLogger();

         /*
        **describe:集中监视Activity生命周期
        */
        this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                addActivity(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                currentActivity = activity;
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                removeActivity(activity);
            }
        });
    }

    // 初始化Bugly
    private void initBugly() {
        //开发期间bug较多 不上传
//        if (BuildConfig.DEBUG) {
//            return;
//        }
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this);
        strategy.setUploadProcess(true);
        Bugly.setIsDevelopmentDevice(this, BuildConfig.DEBUG);

        //升级配置
        Beta.upgradeCheckPeriod = 60 * 1000;        //检查升级周期
        Beta.canNotifyUserRestart = true;           //合成补丁后提醒用户重启

        Bugly.init(this, "1736327650", BuildConfig.DEBUG, strategy);
    }

    /**
     * description:初始化日志打印工具
     */

    private void initLogger() {
    }

    public void addActivity(Activity activity) {
        mList.put(activity.getClass().getSimpleName(), activity);
    }

    /**
     * *describe:移除Activity
     */
    public void removeActivity(Activity activity) {
        mList.remove(activity.getClass().getSimpleName());
    }

    /**
     * *describe:完全退出APP
     */
    public void exit() {
        try {
            for (Map.Entry<String, Activity> entry : mList.entrySet()) {
                entry.getValue().finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    解决64k
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public void exitApp() {
        SPUtils.setIsQuit(true);
        //退出APP后停止接受推送
        JPushInterface.stopPush(this);
        exit();
    }

    public Realm getRealm() {
        return realm;
    }

    /**
     * description:用户被踢下线
     */

    public void kitOut() {
        final NormalDialog dialog = new NormalDialog(currentActivity);
        dialog.content("您的账号在另外的设备登录,是否重新登录?")
                .btnText("直接退出", "重新登录")
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        MyApplication.getInstance().exitApp();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        MyApplication.getInstance().exitApp();
                        Intent intent = new Intent(currentActivity, FlashActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        currentActivity.startActivity(intent);
                    }
                });
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        //用户被踢下线 要关闭MainService  否则MainService还在运行 会继续执行一些后台操作
        try {
            Activity activity = mList.get(MainActivity.class.getSimpleName());
            if (activity != null) {
                ((MainActivity) activity).endService();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * description:token过期
     */

    public void showExpiredDialog() {
        final NormalDialog normalDialog = new NormalDialog(MyApplication.getInstance().currentActivity);
        normalDialog.content("登录信息已过期,请重新登录");
        normalDialog.btnText("取消", "确定")
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        normalDialog.dismiss();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        normalDialog.dismiss();
                        MyApplication.getInstance().exitApp();
                        Intent intent = new Intent(MyApplication.getInstance().currentActivity, FlashActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        MyApplication.getInstance().currentActivity.startActivity(intent);
                    }
                });
        normalDialog.setCancelable(false);
        normalDialog.setCanceledOnTouchOutside(false);
        normalDialog.show();
    }


}
